from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from info import constants, db
from info.models import Category, News
from info.modules.profile import profile_blu
from info.utils.captcha.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET

@profile_blu.route('/news_list')
@user_login_data
def user_news_list():
    # 获取页数
    page = request.args.get("p",1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id==user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())
    data = {
        "news_list":news_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }

    return render_template('news/user_news_list.html',data=data)

@profile_blu.route('/news_release',methods=["GET","POST"])
@user_login_data
def news_release():
    #　加载新闻分类数据
    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_li = []
        for category in categories:
            category_dict_li.append(category.to_dict())
        # 移除最新的分类
        category_dict_li.pop(0)
        return render_template('news/user_news_release.html',data={"categories":category_dict_li})
    # ｐｏｓｔ提交，执行发布新闻操作
    #　获取参数
    title = request.form.get("title")
    source = "个人发布"
    content = request.form.get("content")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    # 判断参数
    if not all([title,source,content,digest,index_image,category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 初始化新闻模型，并设置相关数据
    # 取到图片，将图片上传到七牛云
    try:
        index_image = index_image.read()
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数有误")

    news = News()
    news.title = title
    news.source = source
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.content = content
    news.user_id = g.user.id

    # 1代表待审核状态
    news.status = 1

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="数据上传失败")

    return jsonify(errno=RET.OK,errmsg="OK")

@profile_blu.route('/collection')
@user_login_data
def user_collection():
    #获取参数
    page = request.args.get("p",1)
    #判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    # 查询用户指定的收藏的新闻
    user = g.user
    news_list = []
    total_page = 1
    current_page = 1
    try:
        paginate = user.collection_news.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "total_page":total_page,
        "current_page": current_page,
        "collections": news_dict_li,
    }

    return render_template('news/user_collection.html',data=data)

@profile_blu.route('/pass_info',methods=["GET","POST"])
@user_login_data
def pass_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pass_info.html')
    # 如果是post表示修改密码
    # 获取参数
    new_password = request.json.get("new_password")
    old_password = request.json.get("old_password")

    # 判断参数
    if not all([new_password,old_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 判断旧密码是否正确
    user = g.user
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg="原密码错误")
    #设置新密码
    user.password = new_password

    return jsonify(errno=RET.OK, errmsg="保存OK")


@profile_blu.route('/pic_info',methods=["GET","POST"])
@user_login_data
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": g.user.to_dict()})
    # 如果是post表示修改头像
    # 取到上传的文件
    try:
        avatar = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 上传文件
    try:
        #　使用自己定义的storage方法去进行图片上传
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")
    # 保存头像地址
    user.avatar_url = key

    return jsonify(errno=RET.OK,errmsg="OK",data={"avatar_url":constants.QINIU_DOMIN_PREFIX+key})





@profile_blu.route('/base_info',methods=["GET","POST"])
@user_login_data
def base_info():
    # 不同的请求方式做不同的事情
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": g.user.to_dict()})
    # 代表修改用户数据
    # 1. 获取参数
    nick_name = request.json.get("nick_name")
    gender = request.json.get("gender")
    signature = request.json.get("signature")
    # 2. 判断参数
    if not all([nick_name,gender,signature]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数有误")
    if gender not in ("WOMEN","MAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    # 3.
    user = g.user
    user.gender = gender
    user.nick_name = nick_name
    user.signature = signature
    # 4. 返回响应
    return jsonify(errno=RET.OK, errmsg="更新成功")


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user":user.to_dict()

    }
    return render_template('news/user.html',data=data)